package com.party.mobile.web.controller.member;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.authorization.annotation.Authorization;
import com.party.authorization.manager.impl.RedisTokenManager;
import com.party.common.constant.Constant;
import com.party.common.redis.StringJedis;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.PasswordUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.city.Area;
import com.party.core.model.city.City;
import com.party.core.model.commune.CRouteInfo;
import com.party.core.model.member.*;
import com.party.core.model.partner.PartnerMemberLabel;
import com.party.core.service.city.IAreaService;
import com.party.core.service.city.ICityService;
import com.party.core.service.member.*;
import com.party.core.service.member.util.MemberFormUtil;
import com.party.core.service.partner.IPartnerLabelService;
import com.party.core.service.partner.IPartnerMemberLabelService;
import com.party.core.service.system.ISysConfigService;
import com.party.core.utils.MyBeanUtils;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.member.CopartnerMemberBizService;
import com.party.mobile.biz.member.MemberBizService;
import com.party.mobile.biz.member.MemberGroupBizService;
import com.party.mobile.biz.order.OrderBizService;
import com.party.mobile.biz.verifyCode.VerifyCodeBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.login.input.VerifyCodeLoginInput;
import com.party.mobile.web.dto.login.output.CopyrightOutput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.login.output.MemberOutput;
import com.party.mobile.web.dto.member.input.BindPhoneInput;
import com.party.mobile.web.dto.member.input.FillInfoInput;
import com.party.mobile.web.dto.member.input.PasswordSetInput;
import com.party.mobile.web.dto.member.input.RegisterInput;
import com.party.mobile.web.dto.member.output.AreaOutput;
import com.party.mobile.web.dto.member.output.CityOutput;
import com.party.mobile.web.dto.member.output.IndustryOutput;
import com.party.mobile.web.dto.member.output.MessageSetOutput;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;

/**
 * 会员服务控制层
 * party
 * Created by wei.li
 * on 2016/9/22 0022.
 */

@Controller
@RequestMapping(value = "member/member")
public class MemberController {

    @Autowired
    private IMemberService memberService;

    @Autowired
    private StringJedis stringJedis;

    @Autowired
    private MemberBizService memberBizService;

    @Autowired
    private CopartnerMemberBizService copartnerMemberBizService;

    @Autowired
    private IAreaService areaService;

    @Autowired
    private ICityService cityService;

    @Autowired
    private IIndustryService industryService;

    @Autowired
    private CurrentUserBizService currentUserBizService;

    @Autowired
    private VerifyCodeBizService verifyCodeBizService;

    @Autowired
    private OrderBizService orderBizService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private IPartnerMemberLabelService partnerMemberLabelService;

    @Autowired
    private IPartnerLabelService partnerLabelService;

    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private IThirdPartyUserService thirdPartyUserService;
    @Autowired
    private MemberGroupBizService memberGroupBizService;

    @Autowired
    private RedisTokenManager redisTokenManager;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 会员注册
     *
     * @param registerInput 会员注册输入视图
     * @param result        验证结果
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "/register")
    public AjaxResult register(@Validated RegisterInput registerInput, HttpServletRequest request, BindingResult result) {

        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }

        // 加短信开关
        boolean isNeedVerify = sysConfigService.isVerifySms();
        if (isNeedVerify) {
            boolean isVerify = memberBizService.verifyCode(registerInput.getPhone(),
                    registerInput.getVerifyCode(), registerInput.getCountryCode());
            if (!isVerify) {
                return AjaxResult.error(PartyCode.VERIFY_CODE_ERROR, "手机验证码不一致");
            }
        }

        MemberOutput memberOutput;
        try {
            memberOutput = memberBizService.register(registerInput);
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.setData(memberOutput);
        return ajaxResult;
    }


    /**
     * 忘记密码
     *
     * @param passwordSetInput 密码输入视图
     * @param result           验证结果
     * @return 交互数据
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @ResponseBody
    @RequestMapping(value = "/resetPwd")
    public AjaxResult resetPassword(@Validated PasswordSetInput passwordSetInput, BindingResult result, HttpServletRequest request) {
        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }
        try {
            copartnerMemberBizService.resetPassword(passwordSetInput, request);
            return AjaxResult.success();
        } catch (BusinessException e) {
            return AjaxResult.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("重置密码异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(100, "重置密码异常");
        }
    }

    /**
     * 忘记密码
     *
     * @param passwordSetInput 密码输入视图
     * @param result           验证结果
     * @return 交互数据
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @ResponseBody
    @RequestMapping(value = "/resetPwd/v2")
    public AjaxResult resetPassword(@Validated PasswordSetInput passwordSetInput, BindingResult result, String identityName) {
        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }
        try {
            copartnerMemberBizService.resetPasswordV2(passwordSetInput, identityName);
            return AjaxResult.success();
        } catch (BusinessException e) {
            return AjaxResult.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("重置密码异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(100, "重置密码异常");
        }
    }

    /**
     * 修改密码
     *
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "/changePwd")
    public AjaxResult changePwd(String oldPwd, String newPwd, HttpServletRequest request) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);

            MemberGroup memberGroup = null;
            Member member = null;

            if (null != currentUser.getIsMemberGroup() && YesNoStatus.YES.getCode().equals(currentUser.getIsMemberGroup())) {
                memberGroup = memberGroupService.get(currentUser.getId());
            } else {
                member = memberService.get(currentUser.getId());
            }

            if (null == member && null == memberGroup) {
                return AjaxResult.error(100, "用户不存在");
            }

            if (null != member) {
                if (!PasswordUtils.validatePassword(oldPwd, member.getPassword())) {
                    return AjaxResult.error(PartyCode.USER_PASSWORD_UNMATCH, "旧密码不匹配");
                }

                member.setPassword(PasswordUtils.encryptPassword(newPwd));
                memberService.update(member);
                redisTokenManager.delRelationshipByKey(member.getId());
            } else if (null != memberGroup) {
                if (!PasswordUtils.validatePassword(oldPwd, memberGroup.getPassword())) {
                    return AjaxResult.error(PartyCode.USER_PASSWORD_UNMATCH, "旧密码不匹配");
                }

                memberGroup.setPassword(PasswordUtils.encryptPassword(newPwd));
                memberGroupService.update(memberGroup);
                redisTokenManager.delRelationshipByKey(memberGroup.getId());
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("修改密码异常", e);
            return AjaxResult.error(100, "修改密码异常");
        }
    }

    /**
     * 重置手机号
     *
     * @param phone      手机号
     * @param verifyCode 验证码
     * @param request
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/resetMobile")
    public AjaxResult resetMobile(String phone, String verifyCode, String countryCode, HttpServletRequest request) {
        //参数验证
        if (Strings.isNullOrEmpty(phone)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数错误");
        }

        try {
            memberBizService.resetMobile(phone, verifyCode, countryCode, request);
            return AjaxResult.success();
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        } catch (Exception e) {
            logger.error("重置手机号异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(100, "重置手机号异常");
        }
    }

    /**
     * 重置头像
     *
     * @param logo    用户头像url
     * @param request
     * @return
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/resetAvata")
    public AjaxResult resetAvata(String logo, HttpServletRequest request) {
        //参数验证
        if (Strings.isNullOrEmpty(logo)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数错误");
        }

        try {
            memberBizService.resetAvata(logo, request);
            return AjaxResult.success();
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }
    }

    /**
     * 设置用户资料是否公开
     *
     * @param isOpen  用户资料是否公开，0：否，1：是
     * @param request
     * @return
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/setOpenInfo")
    public AjaxResult setOpenInfo(Integer isOpen, HttpServletRequest request) {
        //参数验证
        if (null == isOpen || isOpen < 0 || isOpen > 1) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数错误");
        }

        try {
            memberBizService.setOpenInfo(isOpen, request);
            return AjaxResult.success();
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }
    }

    /**
     * 获取push消息开关接口
     *
     * @param request
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "/getMsgTips")
    public AjaxResult getMsgTips(HttpServletRequest request) {
        try {
            MessageSetOutput messageSetOutput = memberBizService.getMessageSetInfo(request);
            return AjaxResult.success(messageSetOutput);
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }
    }

    /**
     * 设置点赞push消息开关
     *
     * @param loveTip 点赞开关（0：关，1：开）
     * @param request
     * @return
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/setLoveTip")
    public AjaxResult setLoveTip(Integer loveTip, HttpServletRequest request) {
        //参数验证
        if (null == loveTip || 0 > loveTip || 1 < loveTip) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数错误");
        }

        MessageSetOutput input = new MessageSetOutput();
        input.setLoveTip(loveTip);

        try {
            memberBizService.updateMessageSet(input, request);
            return AjaxResult.success();
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }
    }

    /**
     * 设置评论push消息开关
     *
     * @param commentTip 评论开关（0：关，1：开）
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/setCommentTip")
    public AjaxResult setCommentTip(Integer commentTip, HttpServletRequest request) {
        //参数验证
        if (null == commentTip || 0 > commentTip || 1 < commentTip) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数错误");
        }

        MessageSetOutput input = new MessageSetOutput();
        input.setCommentTip(commentTip);

        try {
            memberBizService.updateMessageSet(input, request);
            return AjaxResult.success();
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }
    }

    /**
     * 设置关注push消息开关
     *
     * @param focusTip 关注开关（0：关，1：开）
     * @param request
     * @return
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/setFocusTip")
    public AjaxResult setFocusTip(Integer focusTip, HttpServletRequest request) {
        //参数验证
        if (null == focusTip || 0 > focusTip || 1 < focusTip) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数错误");
        }

        MessageSetOutput input = new MessageSetOutput();
        input.setFocusTip(focusTip);

        try {
            memberBizService.updateMessageSet(input, request);
            return AjaxResult.success();
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }
    }


    /**
     * 设置系统push消息开关
     *
     * @param sysTip  系统开关（0：关，1：开）
     * @param request
     * @return
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/setSysTip")
    public AjaxResult setSysTip(Integer sysTip, HttpServletRequest request) {
        //参数验证
        if (null == sysTip || 0 > sysTip || 1 < sysTip) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数错误");
        }

        MessageSetOutput input = new MessageSetOutput();
        input.setSysTip(sysTip);

        try {
            memberBizService.updateMessageSet(input, request);
            return AjaxResult.success();
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }
    }

    /**
     * 设置活动push消息开关
     *
     * @param actTip  活动开关（0：关，1：开）
     * @param request
     * @return
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/setActTip")
    public AjaxResult setActTip(Integer actTip, HttpServletRequest request) {
        //参数验证
        if (null == actTip || 0 > actTip || 1 < actTip) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数错误");
        }

        MessageSetOutput input = new MessageSetOutput();
        input.setActTip(actTip);

        try {
            memberBizService.updateMessageSet(input, request);
            return AjaxResult.success();
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }
    }


    /**
     * 设置商品push消息开关
     *
     * @param goodsTip 商品开关（0：关，1：开）
     * @param request
     * @return
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/setGoodsTip")
    public AjaxResult setGoodsTip(Integer goodsTip, HttpServletRequest request) {
        //参数验证
        if (null == goodsTip || 0 > goodsTip || 1 < goodsTip) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数错误");
        }

        MessageSetOutput input = new MessageSetOutput();
        input.setGoodsTip(goodsTip);

        try {
            memberBizService.updateMessageSet(input, request);
            return AjaxResult.success();
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }
    }


    /**
     * 完善用户信息
     *
     * @param bindInput     绑定手机输入视图
     * @param fillInfoInput 输入视图
     * @param result        验证结果
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "/fillInfo")
    public AjaxResult fillInfo(BindPhoneInput bindInput, @Validated FillInfoInput fillInfoInput, BindingResult result, HttpServletRequest request) throws Exception {
        MemberOutput output = null;
        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        try {
            if (!Strings.isNullOrEmpty(bindInput.getMobile())) {
                if (null != currentUser.getIsMemberGroup() && YesNoStatus.YES.getCode().equals(currentUser.getIsMemberGroup())) {
                    currentUser = memberGroupBizService.bindPhoneBiz2(bindInput.getMobile(), bindInput.getVerifyCode(), fillInfoInput.getCountryCode(), request);

                    MemberGroup member = memberGroupService.get(currentUser.getId());
                    member.setCountryCode(fillInfoInput.getCountryCode());
                    memberGroupService.update(member);
                } else {
                    currentUser = memberBizService.bindPhoneBiz2(bindInput.getMobile(), bindInput.getVerifyCode(), fillInfoInput.getCountryCode(), request);

                    Member member = memberService.get(currentUser.getId());
                    member.setCountryCode(fillInfoInput.getCountryCode());
                    memberService.update(member);
                }
            }
            if (null != currentUser.getIsMemberGroup() && YesNoStatus.YES.getCode().equals(currentUser.getIsMemberGroup())) {
                output = memberGroupBizService.fillInfo(fillInfoInput, currentUser.getId());
            } else {
                output = memberBizService.fillInfo(fillInfoInput, currentUser.getId());
            }
            copartnerMemberBizService.hasCopartnerRole(currentUser.getId(), output);
            return AjaxResult.success(output);
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }
    }


    /**
     * 用户信息初始化数据
     *
     * @return 用户信息初始化数据
     */
    @ResponseBody
    @RequestMapping("/InfoInit")
    public AjaxResult InfoInit() {
        List<Area> dbAreaList = areaService.cityLevelAll();
        List<AreaOutput> areaOutputList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(dbAreaList)) {
            areaOutputList = LangUtils.transform(dbAreaList, input -> {
                AreaOutput areaOutput = AreaOutput.transform(input);
                return areaOutput;
            });
        }

        List<Industry> dbIndustryList = industryService.listAll();
        List<IndustryOutput> industryOutputList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(dbIndustryList)) {
            industryOutputList = LangUtils.transform(dbIndustryList, input -> {
                IndustryOutput industryOutput = IndustryOutput.transform(input);
                return industryOutput;
            });
        }

        Map map = new HashMap();
        map.put("areaList", areaOutputList);
        map.put("industryList", industryOutputList);

        return AjaxResult.success(map);
    }


    /**
     * 获取城市信息（用于填写用户信息）
     *
     * @return 信息信息
     */
    @ResponseBody
    @RequestMapping("/areaInfo")
    public AjaxResult areaInfo() {
        List<Area> dbAreaList = areaService.cityLevelAll();

        List<AreaOutput> areaOutputList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(dbAreaList)) {
            areaOutputList = LangUtils.transform(dbAreaList, input -> {
                AreaOutput areaOutput = AreaOutput.transform(input);
                return areaOutput;
            });
        }

        return AjaxResult.success(areaOutputList);
    }

    /**
     * 根据parentId获取省市信息（一级目录, 用于填写用户信息）
     *
     * @param parentId 父节点id
     * @return 信息信息
     */
    @ResponseBody
    @RequestMapping("/getCityInfo")
    public AjaxResult getCityInfo(String parentId) {
        List<Area> dbAreaList = areaService.cityLevelAll();

        List<AreaOutput> areaOutputList = new ArrayList<>();
        for (int i = 0; i < dbAreaList.size(); i++) {
            AreaOutput areaOutput = AreaOutput.transform(dbAreaList.get(i));
            //如果parentId为空，则给出省份列表，否则给出该省份下的所有城市列表
            if (Strings.isNullOrEmpty(parentId)) {
                if (null != areaOutput && "1".equals(areaOutput.getParentId())) {
                    areaOutput.setHaschildren(true);
                    areaOutputList.add(areaOutput);
                }
            } else {
                if (null != areaOutput && parentId.equals(areaOutput.getParentId())) {
                    areaOutput.setHaschildren(false);
                    areaOutputList.add(areaOutput);
                }
            }
        }
        return AjaxResult.success(areaOutputList);
    }


    /**
     * 获取行业信息
     *
     * @return 行业信息列表
     */
    @ResponseBody
    @RequestMapping("/industryInfo")
    public AjaxResult industryInfo() {
        List<Industry> dbIndustryList = industryService.listAll();

        List<IndustryOutput> industryOutputList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(dbIndustryList)) {
            industryOutputList = LangUtils.transform(dbIndustryList, input -> {
                IndustryOutput industryOutput = IndustryOutput.transform(input);
                return industryOutput;
            });
        }

        return AjaxResult.success(industryOutputList);
    }

    /**
     * 根据父节点获取行业信息（一级目录, 用于填写用户信息）
     *
     * @param parentId 父节点id
     * @return 行业信息列表
     */
    @ResponseBody
    @RequestMapping("/getIndustryInfo")
    public AjaxResult getIndustryInfo(String parentId) {
        List<Industry> dbIndustryList = industryService.listAll();

        List<IndustryOutput> industryOutputList = new ArrayList<>();

        for (int i = 0; i < dbIndustryList.size(); i++) {
            IndustryOutput industryOutput = IndustryOutput.transform(dbIndustryList.get(i));
            //如果parentId为空，则给出一级行业列表，否则给出该一级行业下的所有二级行业列表
            if (Strings.isNullOrEmpty(parentId)) {
                if (null != industryOutput && "0".equals(industryOutput.getParentId())) {
                    industryOutput.setHaschildren(true);
                    industryOutputList.add(industryOutput);
                }
            } else {
                if (null != industryOutput && parentId.equals(industryOutput.getParentId())) {
                    industryOutput.setHaschildren(false);
                    industryOutputList.add(industryOutput);
                }
            }
        }

        return AjaxResult.success(industryOutputList);
    }

    /**
     * 获取城市信息(用于筛选活动，商品列表)
     *
     * @return 行业信息列表
     */
    @ResponseBody
    @RequestMapping("/cityInfo")
    public AjaxResult cityInfo() {
        List<City> dbCityList = cityService.listOpen();

        List<CityOutput> cityOutputList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(dbCityList)) {
            cityOutputList = LangUtils.transform(dbCityList, input -> {
                CityOutput cityOutput = CityOutput.transform(input);
                return cityOutput;
            });
        }

        return AjaxResult.success(cityOutputList);
    }

    @ResponseBody
    @Authorization
    @RequestMapping("/memberInfo")
    public AjaxResult memberInfo(String memberId, String partnerId, HttpServletRequest request) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            String orgId = currentUser.getId();

            if (StringUtils.isEmpty(memberId)) {
                memberId = orgId;
            }
            if (StringUtils.isEmpty(partnerId)) {
                partnerId = orgId;
            }

            MemberOutput output = null;
            Member member = memberService.get(memberId);
            MemberGroup memberGroup = memberGroupService.get(memberId);
            if (null == member && null == memberGroup) {
                return AjaxResult.error(100, "用户不存在");
            }

            if (null != member) {
                output = memberBizService.getLoginMember(member);
            } else if (null != memberGroup) {
                if (StringUtils.isEmpty(memberGroup.getCopyrightName())) {
                    memberGroup.setCopyrightName(memberGroup.getRealname());
                }

                /*if (StringUtils.isEmpty(memberGroup.getTechnicalSupport())) {
                    memberGroup.setTechnicalSupport("我也要发起");
                }*/

                output = memberBizService.getLoginMember(memberGroup);
            }

            //增加会员标签字段
            String lableName = "";
            PartnerMemberLabel pmlobj = partnerMemberLabelService.getMemberLabel(partnerId, memberId);
            if (null != pmlobj && StringUtils.isNotBlank(pmlobj.getLabelId())) {
                lableName = partnerLabelService.get(pmlobj.getLabelId()).getLabelName();
            }
            output.setLabelName(lableName);


            //MemberOutput output = MemberOutput.transform(member);
            return AjaxResult.success(output);
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }
    }

    /**
     * 获取机构版权信息
     *
     * @param memberId 机构编号
     * @return 版权信息
     */
    @ResponseBody
    @RequestMapping("copyright")
    public AjaxResult copyright(String memberId) {
        AjaxResult ajaxResult = new AjaxResult();
        if (Strings.isNullOrEmpty(memberId)) {
            ajaxResult.setDescription("参数memberId不能为空");
            ajaxResult.setSuccess(false);
            return ajaxResult;
        }
        MemberGroup member = memberGroupService.get(memberId);
        if (null == member) {
            ajaxResult.setDescription("会员信息不存在");
            ajaxResult.setSuccess(false);
            return ajaxResult;
        }
        if (StringUtils.isEmpty(member.getCopyrightName())) {
            member.setCopyrightName(member.getRealname());
        }
        CopyrightOutput output = CopyrightOutput.transform(member);
        ajaxResult.setSuccess(true);
        ajaxResult.setData(output);
        return ajaxResult;
    }


    /**
     * 获取合作商余额
     *
     * @param request
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("getPartnerBalance")
    public AjaxResult getPartnerBalance(HttpServletRequest request) {
        CurrentUser member = currentUserBizService.getCurrentUser(request);
        Double orderTotal = orderBizService.getOrderTotal(false, member.getId());
        return AjaxResult.success(orderTotal);
    }

    /**
     * 获取城市信息（商城购物地址）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/allAreaInfo")
    public AjaxResult allAreaInfo() {
        List<Area> dbAreaList = areaService.listAll();

        List<AreaOutput> areaOutputList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(dbAreaList)) {
            areaOutputList = LangUtils.transform(dbAreaList, input -> {
                AreaOutput areaOutput = AreaOutput.transform(input);
                return areaOutput;
            });
        }

        return AjaxResult.success(areaOutputList);
    }

    /**
     * 根据手机号获取用户信息
     *
     * @param input  输入参数
     * @param result 验证结果
     * @return
     */

    @ResponseBody
    @RequestMapping("mobile2Member")
    public AjaxResult mobile2Member(@Validated VerifyCodeLoginInput input, boolean isNeedVerify, BindingResult result) {
        AjaxResult ajaxResult = new AjaxResult();

        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }

        if (isNeedVerify) {
            // 加短信开关
            boolean isVerify = sysConfigService.isVerifySms();
            if (isNeedVerify) {
                boolean verify = verifyCodeBizService.verify(input.getPhone(), input.getVerifyCode());
                if (!verify) {
                    return AjaxResult.error(PartyCode.VERIFY_CODE_ERROR, "手机号验证码不一致");
                }
            }
        }
        //查找用户
        Member member = memberService.findByLoginName(input.getPhone(), Member.MEMBER_PERSONAL);
        if (member != null) {
            MemberOutput memberOutput = memberBizService.getLoginMember(member);
            ajaxResult.setData(memberOutput);
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 获取机构的版权信息
     *
     * @param memberId 用户id
     * @return
     */
    @ResponseBody
    @RequestMapping("getCopyrightInfo")
    public AjaxResult getCopyrightInfo(String memberId) {
        if (StringUtils.isEmpty(memberId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "id不能为空");
        }
        try {
            MemberGroup member = memberGroupService.getPartner(memberId);
            if (StringUtils.isEmpty(member.getCopyrightName())) {
                member.setCopyrightName(member.getRealname());
            }
            CopyrightOutput output = new CopyrightOutput();
            MyBeanUtils.copyBeanNotNull2Bean(member, output);
            return AjaxResult.success(output);
        } catch (Exception e) {
            logger.error("获取版权信息异常", e);
            return AjaxResult.error(100, "获取版权信息异常");
        }
    }

    @ResponseBody
    @RequestMapping("expireCheck")
    public AjaxResult expireCheck(String orgId) {
        if (!sysConfigService.isOpenExpirationRestriction()) {
            return AjaxResult.success(false);
        }
        if (StringUtils.isEmpty(orgId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "机构id不能为空");
        }
        try {
            String key = "EXPIRE_DATE_" + orgId;
            String value = stringJedis.getValue(key);

            Date date = null;
            if (StringUtils.isNotEmpty(value)) {
                try {
                    date = DateUtils.parse(value, "yyyy-MM-dd HH:mm:ss");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (null == date) {
                date = MemberFormUtil.getExpirationTimeById(orgId);
                if (null == date) {
                    throw new Exception();
                }
                stringJedis.setValue(key, DateUtils.formatDate(date, "yyyy-MM-dd HH:mm:ss"));
            }
            return AjaxResult.success(MemberFormUtil.isExpire(orgId, date));
        } catch (Exception e) {
            logger.error("获取过期时间异常：memberId-{}", orgId);
            return AjaxResult.success(false);
        }
    }

    /**
     * @Description: 通过手机号删除用户——————只能在测试环境用
     * @Param: [mobile, proofreadCode]
     * @return: com.party.mobile.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/10/24
     */
    @ResponseBody
    @RequestMapping("deleteMember")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult deleteMember(String mobile, String proofreadCode) {
        if (StringUtils.isEmpty(mobile)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "手机号为空");
        }
        if (StringUtils.isEmpty(proofreadCode)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "校对码为空");
        }
        if (!"TXZ_TEST_123".equals(proofreadCode)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "校对码不正确");
        }
        try {
            Member mobileMember = memberService.findByPhone(mobile, Constant.MEMBER_PERSONAL);
            if (mobileMember == null) {
                return AjaxResult.error(PartyCode.DATA_UNEXIST, "手机号不存在");
            }
            //机构关系删除
            PartnerMember partnerMember = new PartnerMember();
            partnerMember.setMemberId(mobileMember.getId());
            List<PartnerMember> list = partnerMemberService.list(partnerMember);
            for (PartnerMember pmObj : list) {
                partnerMemberService.delete(pmObj.getId());
            }
            //授权关系删除
            ThirdPartyUser thirdPartyUser = new ThirdPartyUser();
            thirdPartyUser.setMemberId(mobileMember.getId());
            List<ThirdPartyUser> thirdPartyUsers = thirdPartyUserService.list(thirdPartyUser);
            for (ThirdPartyUser tpuObj : thirdPartyUsers) {
                thirdPartyUserService.delete(tpuObj.getId());
            }
            //member删除
            memberService.delete(mobileMember.getId());
            return AjaxResult.success("删除用户成功，该方法只供测试环境使用");
        } catch (Exception e) {
            logger.error("用户删除异常", e);
            return AjaxResult.success(false);
        }
    }

    /**
     * @Description: 获取分社用户
     * @return: com.party.mobile.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2020/05/08
     */
    @ResponseBody
    @RequestMapping("getMemberGroups")
    public AjaxResult getMemberGroups() {
        List<Map<String, Object>> memberGroups_out = Lists.newArrayList();
        try {
            String xzgsMemberId = memberGroupBizService.getXzgsMemberId();
            List<MemberGroup> memberGroups = memberGroupService.getChildWithMyAndName(xzgsMemberId);
            for (MemberGroup m : memberGroups) {

                Map<String, Object> mmp = Maps.newHashMap();
                mmp.put("id",m.getId());
                mmp.put("username",m.getUsername());
                mmp.put("realname",m.getRealname());
                mmp.put("fullname",m.getFullname());
                memberGroups_out.add(mmp);
            }
            return AjaxResult.success(memberGroups_out);
        } catch (Exception e) {
            logger.error("获取分社列表异常", e);
            return AjaxResult.success(false);
        }
    }
}
